package com.example.springbootlearn.entity;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author caiji Mr. Li
 * @date 2019/11/14 11:36
 */
public class TreeNode {

    Object data;
    TreeNode leftChild;
    TreeNode rightChild;

    //前序排列
    public void preOrderTraversal(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        System.out.println(treeNode.data);
        preOrderTraversal(treeNode.leftChild);
        preOrderTraversal(treeNode.rightChild);
    }

    //中序排列
    public void inOrderTraversal(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        inOrderTraversal(treeNode.leftChild);
        System.out.println(treeNode.data);
        inOrderTraversal(treeNode.rightChild);
    }

    //后序排列
    public void postOrderTraversal(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        postOrderTraversal(treeNode.leftChild);
        postOrderTraversal(treeNode.rightChild);
        System.out.println(treeNode.data);
    }

    //层序排列
    public void levelOrderTraversal(TreeNode treeNode) {
        if (treeNode == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        //添加
        queue.offer(treeNode);
        if (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            System.out.println(node.data);
            if (node.leftChild != null) {
                queue.offer(node.leftChild);
            }
            if (node.rightChild != null) {
                queue.offer(node.rightChild);
            }
        }
    }
}
